﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;
using thinger.DataConvertLib;

namespace SerialPortDemo_07
{
    public class MySerialPort
    {
        private SerialPort _serialPort = new SerialPort();

        // 串口打开标识
        public bool open = false;

        // 接收事件
        public event Action<byte[]> ReceivedEvent;

        // 输出日志事件
        public event Action<string> ShowLogEvent;

        public DataHandler Handler = new DefaultDataHandler(); // 数据处理器

        public void InitBy(ComboBox comboxPortName, ComboBox comboBoxBaudRate)
        {
            string[] port = System.IO.Ports.SerialPort.GetPortNames();

            comboxPortName.Items.AddRange(port);
            // 如果有数据显示第0个
            comboxPortName.SelectedIndex = comboxPortName.Items.Count > 0 ? 0 : -1;

            comboBoxBaudRate.Items.Add(1200);
            comboBoxBaudRate.Items.Add(4800);
            comboBoxBaudRate.Items.Add(9600);
            comboBoxBaudRate.Items.Add(14400);
            comboBoxBaudRate.Items.Add(19200);
            comboBoxBaudRate.Items.Add(38400);

            comboBoxBaudRate.SelectedItem = 9600;

        }

        public void OpenBy(string portName, int baudRate)
        {
            try
            {
                _serialPort.DataReceived += SerialPortDataReceived;
                _serialPort.PortName = portName;
                _serialPort.BaudRate = baudRate;
                _serialPort.DataBits = 8;
                _serialPort.StopBits = StopBits.One;
                _serialPort.Parity = Parity.None;
                _serialPort.Open();

                open = true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void Close()
        {
            try
            {
                _serialPort.Close();

                open = false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void Write(byte[] request)
        {
            try
            {
                Debug.WriteLine("发送请求：" + StringLib.GetHexStringFromByteArray(request));
                ShowLogEvent?.Invoke("发送请求：" + StringLib.GetHexStringFromByteArray(request));

                _serialPort.Write(request, 0, request.Length);
            } catch (Exception)
            {
                throw;
            }
     
        }

        private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                _serialPort = (SerialPort)sender;
                byte[] bytebuffer = new byte[_serialPort.BytesToRead];
                _serialPort.Read(bytebuffer, 0, bytebuffer.Length);

                ByteBuffer byteBuffer = new ByteBuffer();

                if (bytebuffer.Length > 0) Handler?.ReceievdHandle(bytebuffer, byteBuffer); // 使用策略，进行数据处理

                // 处理完成
                if (byteBuffer.CURRENT_LENGTH > 0) {
                    Debug.WriteLine("收到响应：" + StringLib.GetHexStringFromByteArray(byteBuffer.toByteArray()));
                    ShowLogEvent?.Invoke("收到响应：" + StringLib.GetHexStringFromByteArray(byteBuffer.toByteArray()));
                    ReceivedEvent?.Invoke(byteBuffer.toByteArray());
                };
            }
            catch (Exception)
            {
                throw;
            }
        }

    }
}
